About 2909 letters

About 15 minutes

#Python's pattern matching

Pattern matching is a grammatical structure that checks whether a variable matches a certain pattern, controlled by match and case.

# The patterns are checked in order, and only the first matching pattern is executed.
match variable:
    case pattern-1:
        code-block-1
    case pattern-2:
        code-block-2
    ...
    case pattern-n:
        code-block-n
G start Start cond1 Matching pattern-1? start->cond1 code1 code-block-1 cond1->code1 yes cond2 Matching pattern-2? cond1->cond2 no end End code1->end code2 code-block-2 cond2->code2 yes condn Matching pattern-n? cond2->condn no code2->end coden code-block-n condn->coden yes condn->end no coden->end

#Exact matching

The pattern is an exact value, and the variable matches if it is equal to the pattern. For example:

value:int = int(input("Please press 1 for a positive review, press 2 for a negative review, and press 3 for a complaint:"))
match value:
    case 1:
        print("positive review")
    case 2:
        print("negative review")
    case 3:
        print("complaint")
    case _:   # Unconditional match
        print("Invalid input")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

case _: is a wildcard pattern that can match anything and is usually written last as the default action when all other patterns do not match.

#Type matching

The pattern is a type, and the variable matches if it matches that type. For example:

value:str = "233"
match value:
    case int(x): # When matching, value will be assigned to x
        print("The type is integer and the value is", x)
    case str(x):
        print("The type is string and the value is", x)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Condition matching

The pattern is a conditional expression, and the variable matches when it satisfies the expression. For example:

age:int = int(input("Please enter your age:"))
match age:
case x if x < 3: # When matching, value will be assigned to x
        print(x, "years old, baby")
    case x if x < 18:
        print(x, "years old, juvenile")
    case x if x < 44:
        print(x, "years old, youth")
    case x if x < 59:
        print(x, "years old, middle aged")
    case x:     # Unconditional match
        print(x, "years old, elderly")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025